var firestarter = {
  groupCounter: 0,
  maxGroups: 5,
  ioBlock: false,
  nextUpdate: null,
  backOff: 2000,
  backOffMin: 2000,
  backOffMax: 30000,
  updatesUrl: "/updates",
  lastUpdate: 0,
  
  update: function (data) {
    var templ = '<div class="entry group%group_number%">%content%<br /><div class="attribution">by %author% at <a href="%link%" target="_blank">%date%</a></div></div>';
    var i = 0;
    for (i = 0; i < data.length; i++) {
      $("#content").prepend(
        templ.replace("%content%", data[i].content)
             .replace("%author%", data[i].author)
             .replace("%link%", data[i].link)
             .replace("%date%", data[i].updated)
             .replace("%group_number%", firestarter.groupCounter));
    }
    
    if (data.length > 0) {
      firestarter.lastUpdate = data[data.length - 1].updated;
    }

    $(".group" + firestarter.groupCounter).hide().show("blind", {}, 1000);

    if (firestarter.groupCounter >= firestarter.maxGroups) {
      var removeGroup = ".group" + (firestarter.groupCounter - firestarter.maxGroups);
      $(removeGroup).remove();
    }

    firestarter.groupCounter++;
    
    // Update stat display
    $("#groupCount").html(firestarter.groupCounter);
    if (data.length > 1 || data.length == 0) {
      $("#lastItemCount").html(data.length + " items");
    } else {
      $("#lastItemCount").html(data.length + "item");
    } 
  },
  
  getItems: function () {
    // Don't do anything if we're waiting for an XHR
    if (firestarter.ioBlock) return;
    var now = new Date().getTime();
    
    // Check if we should update again
    if (!firestarter.nextUpdate || firestarter.nextUpdate < now) {
      firestarter.ioBlock = true;
      $.ajax({
        url: firestarter.updatesUrl + "?updated=" + firestarter.lastUpdate,
        async: true,
        ifModified: true,
        success: function (data, status, xhr) {
          if (typeof data != 'undefined') {
            firestarter.backOff = firestarter.backOffMin;
            firestarter.update(data);
            console.log(data);
          } else {
            firestarter.backOff *= 2;
            if (firestarter.backOff > firestarter.backOffMax) {
              firestarter.backOff = firestarter.backOffMax;
            }
          }
          
          // Update stat display
          $("#timeout").html(firestarter.backOff);
          firestarter.nextUpdate = now + firestarter.backOff;
          firestarter.ioBlock = false;
        }
      })
    }
  }
};